﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;

namespace TiebaSpider.Setups
{
    public class SetupControl
    {
        public Beans.Options AppOptions { get; set; }
        public Beans.LastBehavier UserLastBehavier { get; set; }

        private readonly string SetupFileLocation;

        public SetupControl()
        {
            AppOptions = new Beans.Options();
            UserLastBehavier = new Beans.LastBehavier();
            SetupFileLocation = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + "TiebaSpider";
            LoadSetupFile();
        }

        private void createSetupFile()
        {
            if (!Directory.Exists(SetupFileLocation))
            {
                Directory.CreateDirectory(SetupFileLocation);
            }
            Directory.SetCurrentDirectory(SetupFileLocation);
            if (!File.Exists("setup.xml"))
            {
                XmlDocument sDoc = new XmlDocument();
                sDoc.AppendChild(sDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));

                XmlElement sEle = sDoc.CreateElement("configuration");
                sDoc.AppendChild(sEle);

                XmlNode sRoot = sDoc.SelectSingleNode("configuration");
                XmlElement optionGroup = sDoc.CreateElement("options");
                sRoot.AppendChild(optionGroup);
                XmlElement behaviorGroup = sDoc.CreateElement("behavior");
                sRoot.AppendChild(behaviorGroup);

                sEle = sDoc.CreateElement("size");
                sEle.SetAttribute("limit", AppOptions.MinSizeLimitation.ToString());
                optionGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("picwidth");
                sEle.SetAttribute("limit", AppOptions.MinWidthLimitation.ToString());
                optionGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("picheight");
                sEle.SetAttribute("limit", AppOptions.MinHeightLimitation.ToString());
                optionGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("store");
                sEle.AppendChild(sDoc.CreateCDataSection(AppOptions.StorageDirectory));
                optionGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("tosub");
                sEle.SetAttribute("switch", AppOptions.StoreInSubdirectory ? "1" : "0");
                optionGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("batchsize");
                sEle.SetAttribute("limit", AppOptions.TaskBatchSize.ToString());
                optionGroup.AppendChild(sEle);
				sEle = sDoc.CreateElement("pagepartition");
				sEle.SetAttribute("amount", AppOptions.PagePartition.ToString());
				optionGroup.AppendChild(sEle);
				sEle = sDoc.CreateElement("timeout");
				sEle.SetAttribute("miliseconds", AppOptions.CrawlerTimeout.ToString());
				optionGroup.AppendChild(sEle);
				sEle = sDoc.CreateElement("hideexists");
				sEle.SetAttribute("switch", AppOptions.StoreInSubdirectory ? "1" : "0");
				optionGroup.AppendChild(sEle);

                sEle = sDoc.CreateElement("onlyonwer");
                sEle.SetAttribute("switch", UserLastBehavier.OnlySeeOwner ? "1" : "0");
                behaviorGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("sizelimit");
                sEle.SetAttribute("switch", UserLastBehavier.EnableSizeLimitation ? "1" : "0");
                behaviorGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("resolutionlimit");
                sEle.SetAttribute("switch", UserLastBehavier.EnableResolutionLimitation ? "1" : "0");
                behaviorGroup.AppendChild(sEle);
                sEle = sDoc.CreateElement("history");
                behaviorGroup.AppendChild(sEle);

                XmlNode historyNode = sDoc.SelectSingleNode("configuration/behavior/history");
                foreach (string historyItem in UserLastBehavier.HistoryForum)
                {
                    sEle = sDoc.CreateElement("item");
                    sEle.AppendChild(sDoc.CreateCDataSection(historyItem));
                    historyNode.AppendChild(sEle);
                }

                sDoc.Save("setup.xml");
            }
        }

        public void LoadSetupFile()
        {
            if (!Directory.Exists(SetupFileLocation))
            {
                Directory.CreateDirectory(SetupFileLocation);
            }
            Directory.SetCurrentDirectory(SetupFileLocation);
            if (File.Exists("setup.xml"))
            {
                XmlDocument sDoc = new XmlDocument();
                sDoc.Load("setup.xml");

                XmlNode dataNode = sDoc.SelectSingleNode("/configuration/options/size");
                AppOptions.MinSizeLimitation = long.Parse(dataNode.Attributes["limit"].Value);
                dataNode = sDoc.SelectSingleNode("/configuration/options/picwidth");
                AppOptions.MinWidthLimitation = int.Parse(dataNode.Attributes["limit"].Value);
                dataNode = sDoc.SelectSingleNode("/configuration/options/picheight");
                AppOptions.MinHeightLimitation = int.Parse(dataNode.Attributes["limit"].Value);
                dataNode = sDoc.SelectSingleNode("/configuration/options/store");
                AppOptions.StorageDirectory = dataNode.InnerText;
                dataNode = sDoc.SelectSingleNode("/configuration/options/tosub");
                AppOptions.StoreInSubdirectory = dataNode.Attributes["switch"].Value.Equals("1");
                dataNode = sDoc.SelectSingleNode("/configuration/options/batchsize");
                AppOptions.TaskBatchSize = int.Parse(dataNode.Attributes["limit"].Value);
				dataNode = sDoc.SelectSingleNode("/configuration/options/pagepartition");
				AppOptions.PagePartition = int.Parse(dataNode.Attributes["amount"].Value);
				dataNode = sDoc.SelectSingleNode("/configuration/options/timeout");
				AppOptions.CrawlerTimeout = int.Parse(dataNode.Attributes["miliseconds"].Value);
				dataNode = sDoc.SelectSingleNode("/configuration/options/hideexists");
				AppOptions.HideExists = dataNode.Attributes["switch"].Value.Equals("1");

                dataNode = sDoc.SelectSingleNode("/configuration/behavior/onlyonwer");
                UserLastBehavier.OnlySeeOwner = dataNode.Attributes["switch"].Value.Equals("1");
                dataNode = sDoc.SelectSingleNode("/configuration/behavior/sizelimit");
                UserLastBehavier.EnableSizeLimitation = dataNode.Attributes["switch"].Value.Equals("1");
                dataNode = sDoc.SelectSingleNode("/configuration/behavior/resolutionlimit");
                UserLastBehavier.EnableResolutionLimitation = dataNode.Attributes["switch"].Value.Equals("1");
                XmlNodeList historyNodes = sDoc.SelectNodes("/configuration/behavior/history/item");
                UserLastBehavier.HistoryForum.Clear();
                foreach (XmlNode item in historyNodes)
                {
                    UserLastBehavier.HistoryForum.Add(item.InnerText);
                }
            }
            else
            {
                createSetupFile();
            }
        }

        public void SaveOptions()
        {
            if (!Directory.Exists(SetupFileLocation))
            {
                Directory.CreateDirectory(SetupFileLocation);
            }
            Directory.SetCurrentDirectory(SetupFileLocation);
            if (File.Exists("setup.xml"))
            {
                XmlDocument sDoc = new XmlDocument();
                sDoc.Load("setup.xml");

                XmlNode editNode = sDoc.SelectSingleNode("/configuration/options/size");
                editNode.Attributes["limit"].Value = AppOptions.MinSizeLimitation.ToString();
                editNode = sDoc.SelectSingleNode("/configuration/options/picwidth");
                editNode.Attributes["limit"].Value = AppOptions.MinWidthLimitation.ToString();
                editNode = sDoc.SelectSingleNode("/configuration/options/picheight");
                editNode.Attributes["limit"].Value = AppOptions.MinHeightLimitation.ToString();
                editNode = sDoc.SelectSingleNode("/configuration/options/batchsize");
                editNode.Attributes["limit"].Value = AppOptions.TaskBatchSize.ToString();
				editNode = sDoc.SelectSingleNode("/configuration/options/pagepartition");
				editNode.Attributes["amount"].Value = AppOptions.PagePartition.ToString();
				editNode = sDoc.SelectSingleNode("/configuration/options/timeout");
				editNode.Attributes["miliseconds"].Value = AppOptions.CrawlerTimeout.ToString();
                editNode = sDoc.SelectSingleNode("/configuration/options/store");
                editNode.RemoveAll();
                editNode.AppendChild(sDoc.CreateCDataSection(AppOptions.StorageDirectory));
                editNode = sDoc.SelectSingleNode("/configuration/options/tosub");
				editNode.Attributes["switch"].Value = AppOptions.StoreInSubdirectory ? "1" : "0";
				editNode = sDoc.SelectSingleNode("/configuration/options/hideexists");
				editNode.Attributes["switch"].Value = AppOptions.HideExists ? "1" : "0";

                sDoc.Save("setup.xml");
            }
            else
            {
                createSetupFile();
            }
        }

        public void SaveBehaviors()
        {
            if (!Directory.Exists(SetupFileLocation))
            {
                Directory.CreateDirectory(SetupFileLocation);
            }
            Directory.SetCurrentDirectory(SetupFileLocation);
            if (File.Exists("setup.xml"))
            {
                XmlDocument sDoc = new XmlDocument();
                sDoc.Load("setup.xml");

                XmlNode editNode = sDoc.SelectSingleNode("/configuration/behavior/onlyonwer");
                editNode.Attributes["switch"].Value = UserLastBehavier.OnlySeeOwner ? "1" : "0";
                editNode = sDoc.SelectSingleNode("/configuration/behavior/sizelimit");
                editNode.Attributes["switch"].Value = UserLastBehavier.EnableSizeLimitation ? "1" : "0";
                editNode = sDoc.SelectSingleNode("/configuration/behavior/resolutionlimit");
                editNode.Attributes["switch"].Value = UserLastBehavier.EnableResolutionLimitation ? "1" : "0";
                editNode = sDoc.SelectSingleNode("/configuration/behavior/history");
                editNode.RemoveAll();
                foreach (string item in UserLastBehavier.HistoryForum)
                {
                    XmlElement sEle = sDoc.CreateElement("item");
                    sEle.AppendChild(sDoc.CreateCDataSection(item));
                    editNode.AppendChild(sEle);
                }

                sDoc.Save("setup.xml");
            }
            else
            {
                createSetupFile();
            }
        }
    }
}
